package com.gzu.se.controller;

import com.gzu.se.entity.Users;
import com.gzu.se.service.UserService;
import com.gzu.se.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtils;

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody Users user) {
        userService.register(user);
        return ResponseEntity.ok("User registered successfully");
    }

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody Users user) {
        Users loggedInUser = userService.login(user.getUsername(), user.getPassword());
        if(loggedInUser != null){
            Map<String, Object> claims=new HashMap<>();
            claims.put("id",loggedInUser.getId());
            return ResponseEntity.ok(jwtUtils.generateToken(claims));
        }else{
            return ResponseEntity.status(500).body("LoginFailed");
        }
    }

    @DeleteMapping("/delete")
    public void deleteUser(@RequestHeader("token") String token) {
        Claims claims= jwtUtils.parseToken(token);
        long id=claims.get("id",Long.class);
        userService.deleteUser(id);
    }

    @PostMapping("/editinfo")
    public void updateUser( @RequestBody Users user,@RequestHeader("token") String token) {
        Claims claims= jwtUtils.parseToken(token);
        long id=claims.get("id",Long.class);
        user.setId(id);
        userService.update(user);
    }

}
